const AdminUser = require('../../models/AdminUser')
const assert = require('http-assert')

const jwt = require('jsonwebtoken')


// 到处一个函数，以便于在server index.js中可以直接将app传进来
module.exports = app => {
    const express = require('express')
    // express子路由
    const router = express.Router({
        mergeParams: true
    })

    // 引用模型
    // const Category = require('../../models/Category')

    // 列表
    router.get('/', async(req, res, next) => {
        // 校验用户是否登录
        const token = String(req.headers.authorization || '').split(' ').pop()
        assert(token, 401, '请先登录')
        const { id } = jwt.verify(token, app.get('secret'))
        assert(id, 401, '请先登录')
        req.user = await AdminUser.findById(id)
        assert(req.user, 401, '请先登录')
        await next();
    }, async(req, res) => {
        const queryOptions = {}
        if(req.Model.modelName === 'Category'){
            queryOptions.populate = 'parent'
        }
        const items = await req.Model.find().setOptions(queryOptions).limit(100)
        res.send(items)
    })
    // 新建
    router.post('/', async(req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })
    // 更新
    router.put('/:id', async(req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })
    // 删除
    router.delete('/:id', async(req, res) => {
        await req.Model.findByIdAndDelete(req.params.id, req.body)
        res.send({
            success: true
        })
    })
    // 获取分类详情id
    router.get('/:id', async(req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })
    app.use('/admin/api/rest/:resource',async(req, res, next) => {
         // 转换名称
         const modelName = require('inflection').classify(req.params.resource)
         // 引入模块
         req.Model = require(`../../models/${modelName}`)
         next()
    } , router)

    // 处理上传文件
    const multer = require('multer')
    const upload = multer({dest: __dirname + '/../../uploads'})
    app.post('/admin/api/upload', async(req, res, next) => {
        // 校验用户是否登录
        const token = String(req.headers.authorization || '').split(' ').pop()
        assert(token, 401, '请先登录')
        const { id } = jwt.verify(token, app.get('secret'))
        assert(id, 401, '请先登录')
        req.user = await AdminUser.findById(id)
        assert(req.user, 401, '请先登录')
        await next();
    },upload.single('file'), async(req, res) => {
        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })

    // 处理登录路由
    app.post('/admin/api/login', async (req, res) => {
        const { username, password } = req.body
        // 1.根据用户名找用户
        const user = await AdminUser.findOne({username}).select('+password')
        assert(user, 422, '用户名不存在')
        // if(!user){
        //     return res.status(422).send({
        //         message: '用户名不存在'
        //     })
        // }
        // 2. 校验密码
        const isVaild = require('bcrypt').compareSync(password, user.password)
        assert(isVaild, 422, '密码错误')
        // if(!isVaild) {
        //     return res.status(422).send({
        //         message: '密码错误'
        //     })
        // }
        // 3. 返回token
        const token = jwt.sign({ id: user._id }, app.get('secret'))
        res.send({ token })
    })

    // 错误处理
    app.use(async (err, req, res ,next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}